package org.jeecg.wms.service.impl;

import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.wms.entity.WmsMatdetailCfg;
import org.jeecg.wms.entity.WmsMatheadValue;
import org.jeecg.wms.mapper.WmsMatdetailCfgMapper;
import org.jeecg.wms.service.IWmsMatdetailCfgService;
import org.jeecg.wms.vo.WmsMatdetailCfgVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WmsMatdetailCfgServiceImpl extends ServiceImpl<WmsMatdetailCfgMapper, WmsMatdetailCfg> implements IWmsMatdetailCfgService {
    @Autowired
    private CommonAPI commonAPI;
    @Override
    public List<WmsMatdetailCfg> getDetailList(WmsMatheadValue wmsMatheadValue) {
        return this.baseMapper.getDetailList(wmsMatheadValue);
    }

    @Override
    public IPage<WmsMatdetailCfgVO> getDetailListBycheckNo(Page<WmsMatdetailCfgVO> page, String checkNo) {
        IPage<WmsMatdetailCfgVO> detailListBycheckNo = this.baseMapper.getDetailListBycheckNo(page, checkNo);
        // 处理检验结果逻辑
        detailListBycheckNo.getRecords().forEach(record -> {
            String datatype = record.getDatatype();
            int wQty = parseStringToInt(record.getWQty()); // 未检验数
            int oQty = parseStringToInt(record.getOQty()); // 合格数
            int nQty = parseStringToInt(record.getNQty()); // NG数
            // 根据数据类型处理结果
            if ("1".equals(datatype)) {
                // 自动检测类型
                record.setResult(determineResultForAutoType(oQty, nQty));
            } else {
                // 手动检测类型
                record.setResult(determineResultForManualType(wQty, nQty));
            }
        });

        return detailListBycheckNo;
    }

    /**
     * 将字符串转换为整数，如果为空则返回0
     * @param value 字符串值
     * @return 整数值
     */
    private int parseStringToInt(String value) {
        try {
            return value == null || value.isEmpty() ? 0 : Integer.parseInt(value);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    /**
     * 确定自动检测类型的结果
     * @param oQty 合格数
     * @param nQty 不合格数
     * @return 结果代码 ("1"-合格, "2"-不合格)
     */
    private String determineResultForAutoType(int oQty, int nQty) {
        if (oQty >= 1) {
            return "1"; // 合格
        } else if (nQty > 0) {
            return "2"; // 不合格
        } else {
            return "1"; // 默认合格
        }
    }

    /**
     * 确定手动检测类型的结果
     * @param wQty 未检验数
     * @param nQty 不合格数
     * @return 结果代码 ("0"-未检验, "1"-合格, "2"-不合格)
     */
    private String determineResultForManualType(int wQty, int nQty) {
        if (wQty > 0) {
            return "0"; // 未检验
        } else if (nQty > 0) {
            return "2"; // 不合格
        } else {
            return "1"; // 合格
        }
    }

    @Override
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<WmsMatdetailCfg> wmsMatdetailCfgClass) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                Integer counterValue222 = commonAPI.getCounterValue("recid.wms_matdetail_cfg","0");
                Integer counterValue3 = commonAPI.getCounterValue("recid.wms_matdetail_cfg","0");
                Integer counterValue4 = commonAPI.getCounterValue("recid.wms_matdetail_cfg","0");
                Integer counterValue5 = commonAPI.getCounterValue("recid.wms_matdetail_cfg","0");
                List<WmsMatdetailCfg> list = ExcelImportUtil.importExcel(file.getInputStream(), wmsMatdetailCfgClass, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                for(int i = 0; i < list.size(); i++){
                    Integer counterValue333 = commonAPI.getCounterValue("recid.wms_matdetail_cfg","0");
                    System.out.println(counterValue333);
                }
//                for (WmsMatdetailCfg item : list){
//                    Integer counterValue = commonAPI.getCounterValue("recid.wms_matdetail_cfg");
//                    item.setRecId(counterValue);
//                    this.baseMapper.insert(item);
//                }
//                list.forEach(item -> {
//                    Integer counterValue = commonAPI.getCounterValue("recid.wms_matdetail_cfg");
//                    item.setRecId(counterValue);
//                    this.baseMapper.insert(item);
//                });
                //service.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                //update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
                String msg = e.getMessage();
                log.error(msg, e);
                if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
                    return Result.error("文件导入失败:有重复数据！");
                } else {
                    return Result.error("文件导入失败:" + e.getMessage());
                }
                //update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

}
